<?php

namespace app\admin\controller;

use app\common\model\Order as OrderModel;
use app\common\model\OrderRefund as OrderRefundModel;
/**
 * 订单退款控制器
 * Class OrderRefund
 * @package app\admin\controller
 */
class OrderRefund extends Base
{
    /**
     * [getIndex  获取退款订单]
     * @param   status 1已退款 0退款审核
     * @return json
     * @author [C。]
     */
    public function getIndex()
    {
        $param = input('param.');
        $model = new OrderRefundModel();
        $this->getPageAndSize($param);
        $map = [];
        $user = $this->user;
        try{
            if(!empty($param['paytype'])){
                $map['o.paytype'] = $param['paytype'];
            }
            if(!empty($param['timetype'])){
                if($param['timetype'] == 1){
                    $map['o.create_time'] = ['between',[strtotime($param['start']),strtotime($param['end'])]];
                }
                if($param['timetype'] == 2){
                    $map['o.paytime'] = ['between',[strtotime($param['start']),strtotime($param['end'])]];
                }
                if($param['timetype'] == 3){
                    $map['o.gotime'] = ['between',[strtotime($param['start']),strtotime($param['end'])]];
                }
                if($param['timetype'] == 4){
                    $map['o.gotime|o.create_time|o.paytime'] = ['between',[strtotime($param['start']),strtotime($param['end'])]];
                }
            }
            if(!empty($param['contype'])){
                if($param['contype'] == 1){
                    $map['o.ordersn'] = $param['con'];
                }
                if($param['contype'] == 2){
                    $map['g.title'] = $param['con'];
                }
            }
            $map['r.status'] = $param['status'];
            $field = 'r.id,o.create_time,o.paytype,o.ordersn,o.price,o.num,o.name,o.tel,o.status,o.people,o.gotime,g.title,g.cover,go.person_num,go.marketprice,r.status rstatus';
            $count = $model->getCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getlist($map,$this->from, $this->size,$field);
            foreach($lists as &$v){
                $v['people'] = json_decode(unserialize($v['people']));
                $v['gotime'] = date('Y-m-d',$v['gotime']);
                if($v['rstatus'] == 0){
                    $v['state'] = '退款中';
                }elseif($v['rstatus'] == 1){
                    $v['state'] = '已退款';
                }
                $v['cover'] = explode(',',$v['cover']);
                $v['cover'] = $v['cover'][0];
            }
        }catch(\Exception $e){
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        if($param['status'] == 0){
            $name = '退款审核';
        }elseif($param['status'] == 1){
            $name = '已退款';
        }
        writelog('查看'.$name.'列表',1,$user);
        return admin_json(1,'获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [postAdd  添加]
     * @return json
     * @author [C。]
     */
    public function postAdd()
    {
        $param = input('param.');
        $model = new OrderRefundModel();
        $omodel = new OrderModel;
        $user = $this->user;
        try{
            $refund = $model->findData($param['orderid'],'orderid','id,status');
            if($refund['status'] === 0){
                return admin_json(-2, '退款正在审核中！');
            }elseif($refund['status'] === 1){
                return admin_json(-3, '已退款成功！');
            }elseif($refund['status'] === 2){
                return admin_json(-4, '已拒绝退款！');
            }elseif($refund['status'] === 3){
                $param['id'] = $refund['id'];
                $param['status'] = 0;
                $param['create_time'] = time();
                $model->editData($param);
                $omodel->editData(['id'=>$param['orderid'],'refundid'=>$refund['id']]);
            }
            if(empty($refund)){
                $param['refundno'] = 'SR'.date('YmdHis').randString();
                $param['reson'] = '拼团失败';
                $id = $model->addData($param);
                $omodel->editData(['id'=>$param['orderid'],'refundid'=>$id]);
            }
        }catch(\Exception $e){
            return admin_json(-1, '添加失败'.$e->getMessage());
        }
        writelog('同意退款',1,$user);
        return admin_json(1, '添加成功');
    }
    /**
     * [postEdit  修改审核]
     * @return json
     * @author [C。]
     */
    public function postEdit()
    {
        $param = input('param.');
        $model = new OrderRefundModel();
        $user = $this->user;
        try{
            $model->editData($param);
        }catch(\Exception $e){
            return admin_json(-1, '修改失败'.$e->getMessage());
        }
        writelog('取消退款',1,$user);
        return admin_json(1, '修改成功');
    }
    /**
     * [getRefund  执行退款]
     * @param
     * @return json
     * @author [C。]
     */
    public function postTorefund()
    {
        $param = input('param.');
        $model = new OrderRefundModel();
        $omodel = new OrderModel();
        $user = $this->user;
        try {
            $refund = $model->findData($param['orderid'],'orderid','id,status,refundno');
            $order = $omodel->findData($param['orderid'], 'id', 'refundid,ordersn,price');
            if(empty($refund)){
                $param['refundno'] = 'SR'.date('YmdHis').randString();
                $param['reson'] = '拼团失败';
                $id = $model->addData($param);
                $omodel->editData(['id'=>$param['orderid'],'refundid'=>$id]);
                $refundno = $param['refundno'];
            }else{
                if($refund['status'] === 0){
                    return admin_json(-2, '退款正在审核中！');
                }elseif($refund['status'] === 1){
                    return admin_json(-3, '已退款成功！');
                }elseif($refund['status'] === 2){
                    return admin_json(-4, '已拒绝退款！');
                }elseif($refund['status'] === 3){
                    $param['id'] = $refund['id'];
                    $param['status'] = 0;
                    $param['create_time'] = time();
                    $model->editData($param);
                    $omodel->editData(['id'=>$param['orderid'],'refundid'=>$refund['id']]);
                    $refundno = $refund['refundno'];
                }
            }
            if($param['paytype'] == 1){
                $appid = config('home.wappid');//福善文化appid
            }else{
                $appid = config('home.kappid');//开放平台appid
            }
            if(empty($param['price'])){
                $price = $order['price'];
            }else{
                $price = $param['price'];
            }
            $mch_id = config('home.fmch_id');  //商户号
            $key = config('home.fmch_secret');  //商户密钥
            $out_trade_no = $order['ordersn'];
            $out_refund_no = $refundno;
            $total_fee = $order['price'] * 100;
            $refund_fee = $price * 100;
            $weixinpay = new \WeixinPay\WeixinRefund($appid,$mch_id, $key, $out_trade_no, $total_fee,$out_refund_no,$refund_fee);
            $return = $weixinpay->refund();
        }catch (\Exception $e) {
            return admin_json(-1, '退款失败' . $e->getMessage());
        }
        if($return){
            if($return['result_code'] == 'FAIL'){
                return admin_json(-1, '退款失败',$return['err_code_des']);
            }else{
                $id = $model->editData(['id'=>$order['refundid'],'status'=>1,'refund_time'=>time()]);
                if(empty($param['price'])){
                    $status = 3;
                }else{
                    $status = 4;
                }
                $omodel->editData(['id'=>$param['id'],'status'=>$status]);
                $return['id'] = $id;
                writelog('退款--'.$id,1,$user);
                return admin_json(1, '退款成功',$return);
            }
        }else{
            return admin_json(-1, '退款失败',$return);
        }
    }
    /**
     * [getRefund  执行退款]
     * @param
     * @return json
     * @author [C。]
     */
    public function postRefund()
    {
        $param = input('param.');
        $model = new OrderRefundModel();
        $omodel = new OrderModel();
        $user = $this->user;
        try {
            $refund = $model->findData($param['id'], 'id', 'refundno,orderid');
            $order = $omodel->findData($refund['orderid'], 'id', 'refundid,ordersn,price');
            
            if($param['paytype'] == 1){
                $appid = config('home.wappid');//福善文化appid
            }else{
                $appid = config('home.kappid');//开放平台appid
            }
            if(empty($param['price'])){
                $price = $order['price'];
            }else{
                $price = $param['price'];
            }
            $mch_id = config('home.fmch_id');  //商户号
            $key = config('home.fmch_secret');  //商户密钥
            $out_trade_no = $order['ordersn'];
            $out_refund_no = $refund['refundno'];
            $total_fee = $price * 100;
            $refund_fee = $price * 100;
            $weixinpay = new \WeixinPay\WeixinRefund($appid,$mch_id, $key, $out_trade_no, $total_fee,$out_refund_no,$refund_fee);
            $return = $weixinpay->refund();
        } catch (\Exception $e) {
            return admin_json(-1, '退款失败' . $e->getMessage());
        }
        if($return){
            if($return['result_code'] == 'FAIL'){
                return admin_json(-1, '退款失败'.$return['err_code_des']);
            }else{
                $id = $model->editData(['id'=>$order['refundid'],'status'=>1,'refund_time'=>time()]);
                if(empty($param['price'])){
                    $status = 3;
                }else{
                    $status = 4;
                }
                $omodel->editData(['id'=>$param['id'],'status'=>$status]);
                $return['id'] = $id;
                writelog('退款--'.$id,1,$user);
                return admin_json(1, '退款成功',$return);
            }
        }else{
            return admin_json(-1, '退款失败',$return);
        }
    }
}